
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import { ServiceResult, Constant } from '@core/constant';
import { ProductSkuEditV2Component } from '@shared/component/product-sku-edit-v2/product-sku-edit-v2.component';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Timeout} from "@shared/descriptor/timeout";
import {spListService} from "../../../../service/spList/spList.service";

@Component({
  selector: 'spList-addone',
  templateUrl: './spList-addone.component.html',
  styleUrls: ['./spList-addone.component.less']
})
export class spListAddoneComponent implements OnInit, OnDestroy {
  orderNo = null;

  private sub: any;

  product:  any = {
    paName:null,//机构名称
    paUser:null,//联系人
    paMobile:null,//电话
    paAddr:null,//机构地址
    paClass:null,//机构等级
    paProfit:null,//平均返佣比例
    paBdate:null,//合作开始时间
    paEdate:null,//合作结束时间
    paSumDkye:null,//贷款余额
    paSumDpf:null,//待赔付
    paSumYjpf:null,//预计赔付
    paSumYpf:null,//已赔付
    paSumBll:null,//不良率
    paM1Byxz:null,//M1本月新增
    paM1Tbz:null,//M1同比值
    paM1Zhye:null,//M1账号余额
    paM2Byxz:null,//M2本月新增
    paM2Tbz:null,//M2同比值
    paM2Zhye:null,//M2账号余额
    paM3Byxz:null,//M3本月新增
    paM3Tbz:null,//M3同比值
    paM3Zhye:null,//M3账号余额
    paM3pByxz:null,//过M3本月新增
    paM3pTbz:null,//过M3同比值
    paM3pZhye:null,//过M3账号余额
    paDpfByxz:null,//待赔付本月新增
    paDpfTbz:null,//待赔付同比值
    paDpfZhye:null,//待赔付账号余额
    paYpfByxz:null,//预赔付本月新增
    paYpfTbz:null,//预赔付同比值
    paYpfZhye:null,//预赔付账号余额
    paBzjYue:null,//保证金余额
    paBzjStatus:null,//保证金状态
    content:null//备注
  };

  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;
  profileForm: FormGroup;

  saleing = false;
  proNos = [];
  cusrIdtypes = [];
  cusGenders = [];
  cusMaritalStatuss = [];
  cusDeus = [];
  cusEthnicals = [];
  bpmStatus = [];
  dyptypes = [];
  dypclasss = [];
  relTypes=[];
  avatarUrl1:string;
  avatarUrl2:string;

  avatarUrl3:string;

  avatarUrl4:string;
  avatarUrl5:string;
  loading = false;
  uploadUrl = '';
  uploadUr5 = '';

  avatarParam1 = { sbtype: '2', filetype:'sb',orderNo: this.orderNo};
  avatarParam2 = { sbtype: '3', filetype:'sb', orderNo: this.orderNo};
  avatarParam3 = { sbtype: '6',  filetype:'sb',orderNo: this.orderNo};
  avatarParam4 = { sbtype: '2', filetype:'sb', orderNo: this.orderNo};
  avatarParam5 = { sbtype: 'No',  filetype:'sp',orderNo: this.orderNo};

  fileList = [ ];


  constructor(
    fb: FormBuilder,
    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private productService: ProductService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private router: Router,
    private cnt: Constant,
    private comm: CommService,
    private spListService: spListService,
  )
    {
      this.titleService.setTitle("添加订单");

    }


  ngOnInit(): void {
    this.loadproNos();
    this.loadcusrIdtypes();
    this.loadcusGenders();
    this.loadcusMaritalStatuss();
    this.loadcusDeus();
    this.loadcusEthnicals();
    this.loadbpmStatus();
    this.loaddyptypes();
    this.loaddypclasss();
    this.loadrelTypes();
    this.uploadUrl = this.productService.uploadsbUrl();
    this.uploadUr5 = this.productService.uploadUrl();
    // this.orderNo = this.comm.getnectno("order");
    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"];
      // 获取商品详情
    });
    this.comm.getno("order").pipe().subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      this.orderNo =  ret['data'];
      this.product.orderNo =  ret['data'];
      console.log("datacezorderNo"+this.orderNo);
      this.avatarParam1 = { sbtype: '2', filetype:'sb',orderNo: this.orderNo};
      this.avatarParam2 = { sbtype: '3', filetype:'sb', orderNo: this.orderNo};
      this.avatarParam3 = { sbtype: '6',  filetype:'sb',orderNo: this.orderNo};
      this.avatarParam4 = { sbtype: '2', filetype:'sb', orderNo: this.orderNo};
      this.avatarParam5 = { sbtype: 'No',  filetype:'jj',orderNo: this.orderNo};
    });
    this.product.cusrIdtype='10';
    this.titleService.setTitle("添加订单");
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 10);

  }
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }
  // 加载产品
  loadproNos() {
    this.proNos = [];
    this.comm.getType("proNo").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
              this.proNos.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载证件类型
  loadcusrIdtypes() {
    this.cusrIdtypes = [];
    this.comm.getType("idType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusrIdtypes.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载性别
  loadcusGenders() {
    this.cusGenders = [];
    this.comm.getType("sex").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusGenders.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载婚姻
  loadcusMaritalStatuss() {
    this.cusMaritalStatuss = [];
    this.comm.getType("marType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusMaritalStatuss.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }

  // 加载学历
  loadcusDeus() {
    this.cusDeus = [];
    this.comm.getType("eduType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusDeus.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }
//加载民族
  loadcusEthnicals() {
    this.cusEthnicals = [];
    this.comm.getType("ethType").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
          for (const row of ret['data']) {
              this.cusEthnicals.push({ text: row.typename, value: row.typecode });
          }
      }
    })
  }
  // 加载证件类型
  loadbpmStatus() {
    this.bpmStatus = [];
    this.comm.getType("bpm_status").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.bpmStatus.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  // 加载证件类型
  loaddyptypes() {
    this.dyptypes = [];
    this.comm.getType("dyptype").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.dyptypes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  loaddypclasss() {
    this.dypclasss = [];
    this.comm.getType("dypclass").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.dypclasss.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  loadrelTypes() {
    this.relTypes = [];
    this.comm.getType("reltype").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.relTypes.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }

  @Timeout(500)
  gotoImg() {
    console.log("+this.orderno"+this.orderNo);
    this.router.navigate(['/prod/product/upload/']);
  }

  reset(i) {

  }

  save(bpmStatus) {

    let fxjPaMainPage = {
      bpmStatus:bpmStatus,
      createBy:this.setting.user.username,
      sysOrgCode:this.setting.user.sysorgCode,
      
      paName:this.product.paName,//机构名称
      paUser:this.product.paUser,//联系人
      paMobile:this.product.paMobile,//电话
      paAddr:this.product.paAddr,//机构地址
      paClass:this.product.paClass,//机构等级
      paProfit:this.product.paProfit,//平均返佣比例
      paBdate:this.product.paBdate,//合作开始时间
      paEdate:this.product.paEdate,//合作结束时间
      paSumDkye:this.product.paSumDkye,//贷款余额
      paSumDpf:this.product.paSumDpf,//待赔付
      paSumYjpf:this.product.paSumYjpf,//预计赔付
      paSumYpf:this.product.paSumYpf,//已赔付
      paSumBll:this.product.paSumBll,//不良率
      paM1Byxz:this.product.paM1Byxz,//M1本月新增
      paM1Tbz:this.product.paM1Tbz,//M1同比值
      paM1Zhye:this.product.paM1Zhye,//M1账号余额
      paM2Byxz:this.product.paM2Byxz,//M2本月新增
      paM2Tbz:this.product.paM2Tbz,//M2同比值
      paM2Zhye:this.product.paM2Zhye,//M2账号余额
      paM3Byxz:this.product.paM3Byxz,//M3本月新增
      paM3Tbz:this.product.paM3Tbz,//M3同比值
      paM3Zhye:this.product.paM3Zhye,//M3账号余额
      paM3pByxz:this.product.paM3pByxz,//过M3本月新增
      paM3pTbz:this.product.paM3pTbz,//过M3同比值
      paM3pZhye:this.product.paM3pZhye,//过M3账号余额
      paDpfByxz:this.product.paDpfByxz,//待赔付本月新增
      paDpfTbz:this.product.paDpfTbz,//待赔付同比值
      paDpfZhye:this.product.paDpfZhye,//待赔付账号余额
      paYpfByxz:this.product.paYpfByxz,//预赔付本月新增
      paYpfTbz:this.product.paYpfTbz,//预赔付同比值
      paYpfZhye:this.product.paYpfZhye,//预赔付账号余额
      paBzjYue:this.product.paBzjYue,//保证金余额
      paBzjStatus:this.product.paBzjStatus,//保证金状态
      content:this.product.content//备注
    };
    console.log(fxjPaMainPage)
    console.log("fxjPaMainPage************"+JSON.stringify(fxjPaMainPage));


    this.loading = true;
    this.spListService.addPro(fxjPaMainPage).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.loading = false;
      if (data.ok === true) {

        this.back();
          this.msg.success("添加成功");
          this.emit.sendMessage("RELOAD_GOODS_LIST");
           } else {
        this.msg.error(data.respMsg);
      }
    })
  }

  back() {
    this.router.navigate(['/prod/product/']);
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`No support: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      this.msg.warning('The pic file not more than 2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  handleChange1(info: { file: UploadFile }) {


    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl1 = img;
        console.log("info1*********"+JSON.stringify(info.file.response[0].piccontent));

        var sfxx=JSON.parse(info.file.response[0].piccontent)

        this.product.cusName=sfxx.result.cardsinfo[0].items[1].content;
        this.product.cusGender=sfxx.result.cardsinfo[0].items[2].content;
        this.product.cusEthnical=sfxx.result.cardsinfo[0].items[3].content;
        this.product.cusBirthday=sfxx.result.cardsinfo[0].items[4].content;
        this.product.cusResAddr=sfxx.result.cardsinfo[0].items[5].content;
        this.product.cusIncard=sfxx.result.cardsinfo[0].items[6].content;
        info.file=null;
      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange2(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }


    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl2 = img;


        var sfxx=JSON.parse(info.file.response[0].piccontent)

        console.log("varfrom*********"+JSON.stringify(sfxx));
        this.product.cusIdValidfrom= sfxx.result.cardsinfo[0].items[3].content;
        this.product.cusIdValidto=sfxx.result.cardsinfo[0].items[4].content;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange3(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl3 = img;

        var sfxx=JSON.parse(info.file.response[0].piccontent)

        this.product.dypname= sfxx.result.cardsinfo[0].items[5].content +"/"+  sfxx.result.cardsinfo[0].items[2].content;

        this.product.dypvalue = sfxx.result.cardsinfo[0].items[1].content;
        this.product.dypyear = sfxx.result.cardsinfo[0].items[3].content;
        this.product.dyptype  =  sfxx.result.cardsinfo[0].items[8].content + "/"+sfxx.result.cardsinfo[0].items[9].content;

        this.product.dypclass =  sfxx.result.cardsinfo[0].items[10].content;

        this.product.dypremark1 = sfxx.result.cardsinfo[0].items[4].content;
        this.product.dypremark2 = sfxx.result.cardsinfo[0].items[6].content;
        this.product.dypremark3   = sfxx.result.cardsinfo[0].items[7].content;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange4(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl4 = img;
        var sfxx=JSON.parse(info.file.response[0].piccontent)

        console.log("varfrom*********"+JSON.stringify(sfxx));
        this.product.emergencyContact=sfxx.result.cardsinfo[0].items[1].content;

        this.product.emergencyResAddr=sfxx.result.cardsinfo[0].items[5].content;
        this.product.emergencyOffice=sfxx.result.cardsinfo[0].items[6].content;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }
  handleChange5(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl5 = img;

      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }


    // 图片 wuwq
    upLoadChange(event) {
      console.log(event);
      let file = event ? event.file : null;
      console.log(file);
      let datas = file && file.id ? file : file.response;
      console.log(datas);
      if (datas) {
          if (event.type == 'success') {
              console.log('ss');
          } else if (event.type == 'removed') {
            console.log('aa');
            let picId = file.id ? file.id : file.response[0].fileId
            this.delPic(picId);
          }
      }
    }
  
  
    // 删除图片 wuwq
    delPic(id) {
      this.productService.delfile(id).pipe(
          catchError(err => {
            return of(err);
          })
        ).subscribe(data => {
          if(data.ok){
            // this.productorder = data.data;
            // console.log(this.productorder);
            // this.reload();
          }else{
            console.log("22")
          }
        })
    }

}
